package com.zjj.wangluo.lianxi.tcp03;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

/**
 * @author zhoujunjie
 * @desc TODO
 * @date
 *
 * 需求3：服务端接收多条消息，服务端也可以发送多条消息；
 * 客户端可以发送多条消息，也可以接收多条消息；（一对一，阻塞的现象）
 *
 * 读 & 写
 */
public class TCPServer {

    public static void main(String[] args) {
        System.out.println("----------服务端-----------");
        try (
                //1.创建服务端套接字
                ServerSocket ss = new ServerSocket(8888);
                //2.接入客户端 阻塞点
                Socket s = ss.accept();
                //读
                BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
                //写
                PrintWriter pw = new PrintWriter(s.getOutputStream());
                Scanner sc = new Scanner(System.in);
        ){
            System.out.println("客户端已成功接入~");

            String str = null;
            while ((str = br.readLine()) != null) {
                //先读
                if(str.equals("886")){
                    System.out.println(s.getRemoteSocketAddress()+"已下线");
                    break;
                }else{
                    System.out.println("服务器读："+str);
                }

                //再写
                System.out.println("服务器说：");
                String string = sc.nextLine();
                pw.println(string);
                pw.flush();

                if(string.equals("886")){
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
